package com.example.micinter_ipcamera;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CAMERA = 10;

    private PreviewView previewView;
    private TextView urlText;
    private Button switchCameraBtn;
    private Button settingsBtn;
    private CameraStreamManager cameraStreamManager;
    private IpCameraServer server;
    private final AtomicReference<byte[]> latestJpeg = new AtomicReference<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        previewView = findViewById(R.id.previewView);
        urlText = findViewById(R.id.urlText);
        switchCameraBtn = findViewById(R.id.switchCameraBtn);
        settingsBtn = findViewById(R.id.settingsBtn);

        cameraStreamManager = new CameraStreamManager(this, previewView, this, latestJpeg);

        switchCameraBtn.setOnClickListener(v -> {
            if (cameraStreamManager != null) {
                cameraStreamManager.switchCamera();
                updateCameraButtonText();
            }
        });

        settingsBtn.setOnClickListener(v -> showSettingsDialog());

        ensurePermissionsThenStart();
    }

    private void updateCameraButtonText() {
        if (cameraStreamManager != null && switchCameraBtn != null) {
            CameraSettings settings = cameraStreamManager.getSettings();
            String text = settings != null && settings.isUseBackCamera() ? "后置摄像头" : "前置摄像头";
            switchCameraBtn.setText(text);
        }
    }

    private void ensurePermissionsThenStart() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQ_CAMERA);
        } else {
            startStreaming();
        }
    }

    private void startStreaming() {
        cameraStreamManager.startCamera();
        int port = IpCameraServer.DEFAULT_PORT;
        server = new IpCameraServer(port, latestJpeg);
        try {
            server.start(0, true);
        } catch (Exception e) {
            // ignore
        }
        updateUrlText();
        updateCameraButtonText();
    }

    private void updateUrlText() {
        String ip = getLocalIpv4Address();
        int port = IpCameraServer.DEFAULT_PORT;
        String url = ip == null ? "未连接到WiFi" : ("http://" + ip + ":" + port + "/");
        if (cameraStreamManager != null) {
            CameraSettings settings = cameraStreamManager.getSettings();
            String resolution = settings != null ? settings.getResolution().getLabel() : "640x480";
            String quality = settings != null ? settings.getQuality().toString() : "中";
            urlText.setText("访问地址: " + url + "\n" +
                    "分辨率: " + resolution + " | 质量: " + quality + "\n" +
                    "MJPEG流: " + (ip != null ? "http://" + ip + ":" + port + "/mjpeg" : "不可用"));
        } else {
            urlText.setText("在同一WiFi下，用浏览器访问: " + url + "\n(MJPEG流: /mjpeg)");
        }
    }

    private void showSettingsDialog() {
        if (cameraStreamManager == null) return;

        CameraSettings settings = cameraStreamManager.getSettings();
        CameraSettings.Resolution[] resolutions = CameraSettings.Resolution.values();
        CameraSettings.Quality[] qualities = CameraSettings.Quality.values();

        // 创建分辨率标签数组
        String[] resolutionLabels = new String[resolutions.length];
        int currentResolutionIndex = 0;
        for (int i = 0; i < resolutions.length; i++) {
            resolutionLabels[i] = resolutions[i].getLabel();
            if (resolutions[i] == settings.getResolution()) {
                currentResolutionIndex = i;
            }
        }

        // 创建质量标签数组
        String[] qualityLabels = new String[qualities.length];
        int currentQualityIndex = 0;
        for (int i = 0; i < qualities.length; i++) {
            qualityLabels[i] = qualities[i].toString();
            if (qualities[i] == settings.getQuality()) {
                currentQualityIndex = i;
            }
        }

        // 创建分辨率选择对话框
        new AlertDialog.Builder(this)
                .setTitle("选择分辨率")
                .setSingleChoiceItems(resolutionLabels, currentResolutionIndex, null)
                .setPositiveButton("确定", (dialog, which) -> {
                    int selected = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    if (selected >= 0 && selected < resolutions.length) {
                        settings.setResolution(resolutions[selected]);
                        showQualityDialog(settings);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void showQualityDialog(CameraSettings settings) {
        CameraSettings.Quality[] qualities = CameraSettings.Quality.values();
        String[] qualityLabels = new String[qualities.length];
        int currentQualityIndex = 0;
        for (int i = 0; i < qualities.length; i++) {
            qualityLabels[i] = qualities[i].toString();
            if (qualities[i] == settings.getQuality()) {
                currentQualityIndex = i;
            }
        }

        new AlertDialog.Builder(this)
                .setTitle("选择JPEG质量")
                .setSingleChoiceItems(qualityLabels, currentQualityIndex, null)
                .setPositiveButton("确定", (dialog, which) -> {
                    int selected = ((AlertDialog) dialog).getListView().getCheckedItemPosition();
                    if (selected >= 0 && selected < qualities.length) {
                        settings.setQuality(qualities[selected]);
                        // 应用所有设置
                        cameraStreamManager.setSettings(settings);
                        updateUrlText();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private String getLocalIpv4Address() {
        try {
            for (NetworkInterface nif : Collections.list(NetworkInterface.getNetworkInterfaces())) {
                if (!nif.isUp() || nif.isLoopback()) continue;
                for (InetAddress addr : Collections.list(nif.getInetAddresses())) {
                    if (!addr.isLoopbackAddress() && addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }
        } catch (Exception ignored) { }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (server != null) {
            server.stop();
            server = null;
        }
        if (cameraStreamManager != null) {
            cameraStreamManager.stopCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQ_CAMERA) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startStreaming();
            } else {
                urlText.setText("需要相机权限来启动视频流");
            }
        }
    }
}